import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Table, Button, Alert, Spinner, Modal } from 'react-bootstrap';
import { getReportList, getReportUrl, deleteReport } from '../services/api';

const ReportsTab = ({ refreshTrigger }) => {
  const [reports, setReports] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');
  const [selectedReport, setSelectedReport] = useState(null);
  const [showDeleteModal, setShowDeleteModal] = useState(false);
  const [reportToDelete, setReportToDelete] = useState(null);
  
  // 加载报告列表
  const loadReports = async () => {
    setLoading(true);
    setError('');
    
    try {
      const response = await getReportList();
      
      if (response.success) {
        setReports(response.data || []);
      } else {
        setError(response.error || '获取报告列表失败');
      }
    } catch (err) {
      setError(err.error || '获取报告列表请求失败');
    } finally {
      setLoading(false);
    }
  };
  
  // 首次加载报告列表
  useEffect(() => {
    loadReports();
  }, []);
  
  // 当refreshTrigger变化时重新加载报告列表
  useEffect(() => {
    if (refreshTrigger !== undefined) {
      // 添加日志方便调试
      console.log('刷新历史回测报告列表');
      loadReports();
    }
  }, [refreshTrigger]);
  
  // 查看报告
  const handleViewReport = (report) => {
    setSelectedReport(report);
  };
  
  // 关闭报告查看
  const handleCloseReport = () => {
    setSelectedReport(null);
  };
  
  // 显示删除确认
  const handleDeleteClick = (report) => {
    setReportToDelete(report);
    setShowDeleteModal(true);
  };
  
  // 确认删除报告
  const confirmDelete = async () => {
    if (!reportToDelete) return;
    
    try {
      const response = await deleteReport(reportToDelete.id);
      
      if (response.success) {
        setSuccess(`报告"${reportToDelete.id}"已成功删除`);
        // 刷新报告列表
        loadReports();
      } else {
        setError(response.error || '删除报告失败');
      }
    } catch (err) {
      setError(err.error || '删除报告请求失败');
    } finally {
      setShowDeleteModal(false);
      setReportToDelete(null);
    }
  };
  
  // 取消删除
  const cancelDelete = () => {
    setShowDeleteModal(false);
    setReportToDelete(null);
  };
  
  return (
    <div>
      <Row>
        <Col md={12}>
          <Card>
            <Card.Header className="d-flex justify-content-between align-items-center">
              <span>历史回测报告</span>
              <Button 
                variant="outline-primary" 
                size="sm" 
                onClick={loadReports}
                disabled={loading}
              >
                {loading ? (
                  <>
                    <Spinner as="span" animation="border" size="sm" className="me-1" />
                    加载中...
                  </>
                ) : '刷新'}
              </Button>
            </Card.Header>
            <Card.Body>
              {error && <Alert variant="danger">{error}</Alert>}
              {success && <Alert variant="success">{success}</Alert>}
              
              {loading && !error ? (
                <div className="text-center p-4">
                  <Spinner animation="border" role="status">
                    <span className="visually-hidden">加载中...</span>
                  </Spinner>
                  <p className="mt-2">正在加载报告列表...</p>
                </div>
              ) : (
                <>
                  {reports.length === 0 ? (
                    <Alert variant="info">
                      暂无历史回测报告。请在"回测设置"标签页中执行回测生成报告。
                    </Alert>
                  ) : (
                    <div className="table-responsive">
                      <Table striped bordered hover>
                        <thead>
                          <tr>
                            <th>报告ID</th>
                            <th>创建时间</th>
                            <th style={{ width: '180px' }}>操作</th>
                          </tr>
                        </thead>
                        <tbody>
                          {reports.map((report) => (
                            <tr key={report.id}>
                              <td>{report.id}</td>
                              <td>{report.creation_date}</td>
                              <td>
                                <Button 
                                  variant="primary" 
                                  size="sm" 
                                  className="me-2"
                                  onClick={() => handleViewReport(report)}
                                >
                                  查看
                                </Button>
                                <Button 
                                  variant="danger" 
                                  size="sm"
                                  onClick={() => handleDeleteClick(report)}
                                >
                                  删除
                                </Button>
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </Table>
                    </div>
                  )}
                </>
              )}
            </Card.Body>
          </Card>
        </Col>
      </Row>
      
      {/* 报告查看模态框 */}
      <Modal 
        show={selectedReport !== null} 
        onHide={handleCloseReport}
        size="xl"
        centered
      >
        <Modal.Header closeButton>
          <Modal.Title>回测报告: {selectedReport?.id}</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          {selectedReport && (
            <iframe 
              src={getReportUrl(selectedReport.id)}
              title="回测报告" 
              className="report-iframe"
            />
          )}
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={handleCloseReport}>
            关闭
          </Button>
        </Modal.Footer>
      </Modal>
      
      {/* 删除确认模态框 */}
      <Modal
        show={showDeleteModal}
        onHide={cancelDelete}
        centered
      >
        <Modal.Header closeButton>
          <Modal.Title>确认删除</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <p>您确定要删除报告"{reportToDelete?.id}"吗？此操作无法撤销。</p>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="secondary" onClick={cancelDelete}>
            取消
          </Button>
          <Button variant="danger" onClick={confirmDelete}>
            确认删除
          </Button>
        </Modal.Footer>
      </Modal>
    </div>
  );
};

export default ReportsTab;
